package com.hbsi.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 程奕红
 * @version 1.0
 */
public class ConnectionFactory {

    private static String driver;
    private static String url;
    private static String username;
    private static String  password;
    //get connection()          返回连接对象
    //静态代码块   负责载入驱动
    static{
        //读db.properties属性文件，将其中的key=value读出来
        Properties properties=new Properties();
        try {
            properties.load(ConnectionFactory.class.getClassLoader().getResourceAsStream("db.properties"));
            driver=properties.getProperty("jdbc.driver");
            url=properties.getProperty("jdbc.url");
            username=properties.getProperty("jdbc.username");
            password=properties.getProperty("jdbc.password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    //getConnection - - ->getConnection
    public static Connection getConnection(){
        Connection con= null;
        try {
            con = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }


}
